package com.xcc.core.lock;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class ZKAbstractLock implements Lock{

    public void getLock() throws Exception {
        String threadName = Thread.currentThread().getName();
        if (lock()) {
            System.out.println(threadName+"-获取锁成功");
        }else {
            System.out.println(threadName+"-获取锁失败，进行等待...");
            waitLock();
            //递归重新获取锁
            getLock();
        }
    }
    
    Comparator<String> nameComparator = (x, y) -> {
        Integer xs = getSequence(x);
        Integer ys = getSequence(y);
        return xs > ys ? 1 : (xs < ys ? -1 : 0);
    };
    
    public Integer getSequence(String name) {
        return Integer.valueOf(name.substring(name.lastIndexOf("-") + 1));
    }

    
    //判断是否有写锁
    public Boolean canAcquireLock(String name, 
                                   List<String> nodes) {
        if (isFirstNode(name, nodes)) {
            return true;
        }
        for (String n : nodes) {
            if(name.equalsIgnoreCase(n)) {
                return true;
            }
            if (n.contains("write")) {
                return false;
            }  
        }
        return true;
        
    }

    
    
    
    
    
    
    public Boolean isFirstNode(String name, List<String> nodes) {
        return nodes.get(0).equals(name.substring(name.lastIndexOf("/") + 1));
    }
    public abstract void waitLock() throws Exception;
    
    
    
    
}
